%matplotlib inline
#https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
Author: Nathan Inkawhich <https://github.com/inkawhich>__
This tutorial will give an introduction to DCGANs through an example. We
will train a generative adversarial network (GAN) to generate new
celebrities after showing it pictures of many real celebrities. Most of
the code here is from the dcgan implementation in
pytorch/examples <https://github.com/pytorch/examples>__, and this
document will give a thorough explanation of the implementation and shed
light on how and why this model works. But don’t worry, no prior
knowledge of GANs is required, but it may require a first-timer to spend
some time reasoning about what is actually happening under the hood.
Also, for the sake of time it will help to have a GPU, or two. Lets
start from the beginning.
What is a GAN?
GANs are a framework for teaching a DL model to capture the training
data’s distribution so we can generate new data from that same
distribution. GANs were invented by Ian Goodfellow in 2014 and first
described in the paper `Generative Adversarial
Nets <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`__.
They are made of two distinct models, a *generator* and a
*discriminator*. The job of the generator is to spawn ‘fake’ images that
look like the training images. The job of the discriminator is to look
at an image and output whether or not it is a real training image or a
fake image from the generator. During training, the generator is
constantly trying to outsmart the discriminator by generating better and
better fakes, while the discriminator is working to become a better
detective and correctly classify the real and fake images. The
equilibrium of this game is when the generator is generating perfect
fakes that look as if they came directly from the training data, and the
discriminator is left to always guess at 50% confidence that the
generator output is real or fake.
Now, lets define some notation to be used throughout tutorial starting
with the discriminator. Let $x$ be data representing an image.
$D(x)$ is the discriminator network which outputs the (scalar)
probability that $x$ came from training data rather than the
generator. Here, since we are dealing with images, the input to
$D(x)$ is an image of CHW size 3x64x64. Intuitively, $D(x)$
should be HIGH when $x$ comes from training data and LOW when
$x$ comes from the generator. $D(x)$ can also be thought of
as a traditional binary classifier.
For the generator’s notation, let $z$ be a latent space vector
sampled from a standard normal distribution. $G(z)$ represents the
generator function which maps the latent vector $z$ to data-space.
The goal of $G$ is to estimate the distribution that the training
data comes from ($p_{data}$) so it can generate fake samples from
that estimated distribution ($p_g$).
So, $D(G(z))$ is the probability (scalar) that the output of the
generator $G$ is a real image. As described in `Goodfellow’s
paper <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`__,
$D$ and $G$ play a minimax game in which $D$ tries to
maximize the probability it correctly classifies reals and fakes
($logD(x)$), and $G$ tries to minimize the probability that
$D$ will predict its outputs are fake ($log(1-D(G(z)))$).
From the paper, the GAN loss function is
\begin{align}\underset{G}{\text{min}} \underset{D}{\text{max}}V(D,G) = \mathbb{E}_{x\sim p_{data}(x)}\big[logD(x)\big] + \mathbb{E}_{z\sim p_{z}(z)}\big[log(1-D(G(z)))\big]\end{align}
In theory, the solution to this minimax game is where
$p_g = p_{data}$, and the discriminator guesses randomly if the
inputs are real or fake. However, the convergence theory of GANs is
still being actively researched and in reality models do not always
train to this point.
What is a DCGAN?
~~
A DCGAN is a direct extension of the GAN described above, except that it
explicitly uses convolutional and convolutional-transpose layers in the
discriminator and generator, respectively. It was first described by
Radford et. al. in the paper Unsupervised Representation Learning With
Deep Convolutional Generative Adversarial
Networks <https://arxiv.org/pdf/1511.06434.pdf>. The discriminator
is made up of strided
convolution <https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d>
layers, batch
norm <https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm2d>
layers, and
LeakyReLU <https://pytorch.org/docs/stable/nn.html#torch.nn.LeakyReLU>
activations. The input is a 3x64x64 input image and the output is a
scalar probability that the input is from the real data distribution.
The generator is comprised of
convolutional-transpose <https://pytorch.org/docs/stable/nn.html#torch.nn.ConvTranspose2d>
layers, batch norm layers, and
ReLU <https://pytorch.org/docs/stable/nn.html#relu> activations. The
input is a latent vector, $z$, that is drawn from a standard
normal distribution and the output is a 3x64x64 RGB image. The strided
conv-transpose layers allow the latent vector to be transformed into a
volume with the same shape as an image. In the paper, the authors also
give some tips about how to setup the optimizers, how to calculate the
loss functions, and how to initialize the model weights, all of which
will be explained in the coming sections.
from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
# Set random seed for reproducibility
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
Random Seed: 999
<torch._C.Generator at 0x20efd4e1610>
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
Let’s define some inputs for the run:
here <https://github.com/pytorch/examples/issues/70>__ for more
details# Root directory for dataset
dataroot = "imgs/img2/portraitdataset"
# Number of workers for dataloader
workers = 2
# Batch size during training
batch_size = 128
# Spatial size of training images. All images will be resized to this
# size using a transformer.
image_size = 64
# Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 100
# Size of feature maps in generator
ngf = 64
# Size of feature maps in discriminator
ndf = 64
# Number of training epochs
num_epochs = 30
# Learning rate for optimizers
lr = 0.0002
# Beta1 hyperparam for Adam optimizers
beta1 = 0.5
# Number of GPUs available. Use 0 for CPU mode.
ngpu = 1
In this tutorial we will use the Celeb-A Faces
dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html> which can
be downloaded at the linked site, or in Google
Drive <https://drive.google.com/drive/folders/0B7EVK8r0v71pTUZsaXdaSnZBZzg>.
The dataset will download as a file named img_align_celeba.zip. Once
downloaded, create a directory named celeba and extract the zip file
into that directory. Then, set the dataroot input for this notebook to
the celeba directory you just created. The resulting directory
structure should be:
::
/path/to/celeba
-> img_align_celeba
-> 188242.jpg
-> 173822.jpg
-> 284702.jpg
-> 537394.jpg
...
This is an important step because we will be using the ImageFolder dataset class, which requires there to be subdirectories in the dataset’s root folder. Now, we can create the dataset, create the dataloader, set the device to run on, and finally visualize some of the training data.
# We can use an image folder dataset the way we have it setup.
# Create the dataset
dataset = dset.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
# Create the dataloader
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=True, num_workers=workers)
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# Plot some training images
real_batch = next(iter(dataloader))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:2], padding=0, normalize=True).cpu(),(1,2,0)))
# plt.imshow(np.transpose(real_batch[0][:64]))
<matplotlib.image.AxesImage at 0x21365fad210>
With our input parameters set and the dataset prepared, we can now get into the implementation. We will start with the weight initialization strategy, then talk about the generator, discriminator, loss functions, and training loop in detail.
Weight Initialization
~~~~~
From the DCGAN paper, the authors specify that all model weights shall
be randomly initialized from a Normal distribution with mean=0,
stdev=0.02. The weights_init function takes an initialized model as
input and reinitializes all convolutional, convolutional-transpose, and
batch normalization layers to meet this criteria. This function is
applied to the models immediately after initialization.
# custom weights initialization called on netG and netD
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
Generator
~~~~~
The generator, $G$, is designed to map the latent space vector ($z$) to data-space. Since our data are images, converting $z$ to data-space means ultimately creating a RGB image with the same size as the training images (i.e. 3x64x64). In practice, this is accomplished through a series of strided two dimensional convolutional transpose layers, each paired with a 2d batch norm layer and a relu activation. The output of the generator is fed through a tanh function to return it to the input data range of $[-1,1]$. It is worth noting the existence of the batch norm functions after the conv-transpose layers, as this is a critical contribution of the DCGAN paper. These layers help with the flow of gradients during training. An image of the generator from the DCGAN paper is shown below.
.. figure:: /_static/img/dcgan_generator.png :alt: dcgan_generator
Notice, how the inputs we set in the input section (nz, ngf, and nc) influence the generator architecture in code. nz is the length of the z input vector, ngf relates to the size of the feature maps that are propagated through the generator, and nc is the number of channels in the output image (set to 3 for RGB images). Below is the code for the generator.
# Generator Code
class Generator(nn.Module):
def __init__(self, ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
nn.Tanh()
# state size. (nc) x 64 x 64
)
def forward(self, input):
return self.main(input)
Now, we can instantiate the generator and apply the weights_init
function. Check out the printed model to see how the generator object is
structured.
# Create the generator
netG = Generator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.02.
netG.apply(weights_init)
# Print the model
print(netG)
Generator(
(main): Sequential(
(0): ConvTranspose2d(100, 512, kernel_size=(4, 4), stride=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(inplace=True)
(3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(4): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU(inplace=True)
(6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(7): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(8): ReLU(inplace=True)
(9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(10): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(11): ReLU(inplace=True)
(12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(13): Tanh()
)
)
Discriminator
~~~~~
As mentioned, the discriminator, $D$, is a binary classification network that takes an image as input and outputs a scalar probability that the input image is real (as opposed to fake). Here, $D$ takes a 3x64x64 input image, processes it through a series of Conv2d, BatchNorm2d, and LeakyReLU layers, and outputs the final probability through a Sigmoid activation function. This architecture can be extended with more layers if necessary for the problem, but there is significance to the use of the strided convolution, BatchNorm, and LeakyReLUs. The DCGAN paper mentions it is a good practice to use strided convolution rather than pooling to downsample because it lets the network learn its own pooling function. Also batch norm and leaky relu functions promote healthy gradient flow which is critical for the learning process of both $G$ and $D$.
Discriminator Code
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf) x 32 x 32
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*2) x 16 x 16
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*4) x 8 x 8
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*8) x 4 x 4
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input)
Now, as with the generator, we can create the discriminator, apply the
weights_init function, and print the model’s structure.
# Create the Discriminator
netD = Discriminator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
netD.apply(weights_init)
# Print the model
print(netD)
Discriminator(
(main): Sequential(
(0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): LeakyReLU(negative_slope=0.2, inplace=True)
(2): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(3): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(4): LeakyReLU(negative_slope=0.2, inplace=True)
(5): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(7): LeakyReLU(negative_slope=0.2, inplace=True)
(8): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(9): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(10): LeakyReLU(negative_slope=0.2, inplace=True)
(11): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), bias=False)
(12): Sigmoid()
)
)
Loss Functions and Optimizers
~~~~~~~~~
With $D$ and $G$ setup, we can specify how they learn
through the loss functions and optimizers. We will use the Binary Cross
Entropy loss
(BCELoss <https://pytorch.org/docs/stable/nn.html#torch.nn.BCELoss>__)
function which is defined in PyTorch as:
Notice how this function provides the calculation of both log components in the objective function (i.e. $log(D(x))$ and $log(1-D(G(z)))$). We can specify what part of the BCE equation to use with the $y$ input. This is accomplished in the training loop which is coming up soon, but it is important to understand how we can choose which component we wish to calculate just by changing $y$ (i.e. GT labels).
Next, we define our real label as 1 and the fake label as 0. These labels will be used when calculating the losses of $D$ and $G$, and this is also the convention used in the original GAN paper. Finally, we set up two separate optimizers, one for $D$ and one for $G$. As specified in the DCGAN paper, both are Adam optimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track of the generator’s learning progression, we will generate a fixed batch of latent vectors that are drawn from a Gaussian distribution (i.e. fixed_noise) . In the training loop, we will periodically input this fixed_noise into $G$, and over the iterations we will see images form out of the noise.
# Initialize BCELoss function
criterion = nn.BCELoss()
# Create batch of latent vectors that we will use to visualize
# the progression of the generator
fixed_noise = torch.randn(64, nz, 1, 1, device=device)
# Establish convention for real and fake labels during training
real_label = 1.
fake_label = 0.
# Setup Adam optimizers for both G and D
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
Training
~~~~
Finally, now that we have all of the parts of the GAN framework defined,
we can train it. Be mindful that training GANs is somewhat of an art
form, as incorrect hyperparameter settings lead to mode collapse with
little explanation of what went wrong. Here, we will closely follow
Algorithm 1 from Goodfellow’s paper, while abiding by some of the best
practices shown in ganhacks <https://github.com/soumith/ganhacks>__.
Namely, we will “construct different mini-batches for real and fake”
images, and also adjust G’s objective function to maximize
$logD(G(z))$. Training is split up into two main parts. Part 1
updates the Discriminator and Part 2 updates the Generator.
Part 1 - Train the Discriminator
Recall, the goal of training the discriminator is to maximize the probability of correctly classifying a given input as real or fake. In terms of Goodfellow, we wish to “update the discriminator by ascending its stochastic gradient”. Practically, we want to maximize $log(D(x)) + log(1-D(G(z)))$. Due to the separate mini-batch suggestion from ganhacks, we will calculate this in two steps. First, we will construct a batch of real samples from the training set, forward pass through $D$, calculate the loss ($log(D(x))$), then calculate the gradients in a backward pass. Secondly, we will construct a batch of fake samples with the current generator, forward pass this batch through $D$, calculate the loss ($log(1-D(G(z)))$), and accumulate the gradients with a backward pass. Now, with the gradients accumulated from both the all-real and all-fake batches, we call a step of the Discriminator’s optimizer.
Part 2 - Train the Generator
As stated in the original paper, we want to train the Generator by minimizing $log(1-D(G(z)))$ in an effort to generate better fakes. As mentioned, this was shown by Goodfellow to not provide sufficient gradients, especially early in the learning process. As a fix, we instead wish to maximize $log(D(G(z)))$. In the code we accomplish this by: classifying the Generator output from Part 1 with the Discriminator, computing G’s loss using real labels as GT, computing G’s gradients in a backward pass, and finally updating G’s parameters with an optimizer step. It may seem counter-intuitive to use the real labels as GT labels for the loss function, but this allows us to use the $log(x)$ part of the BCELoss (rather than the $log(1-x)$ part) which is exactly what we want.
Finally, we will do some statistic reporting and at the end of each epoch we will push our fixed_noise batch through the generator to visually track the progress of G’s training. The training statistics reported are:
Note: This step might take a while, depending on how many epochs you run and if you removed some data from the dataset.
# Training Loop
# Lists to keep track of progress
img_list = []
G_losses = []
D_losses = []
iters = 0
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
# For each batch in the dataloader
for i, data in enumerate(dataloader, 0):
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
## Train with all-real batch
netD.zero_grad()
# Format batch
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), real_label, dtype=torch.float, device=device)
# Forward pass real batch through D
output = netD(real_cpu).view(-1)
# Calculate loss on all-real batch
errD_real = criterion(output, label)
# Calculate gradients for D in backward pass
errD_real.backward()
D_x = output.mean().item()
## Train with all-fake batch
# Generate batch of latent vectors
noise = torch.randn(b_size, nz, 1, 1, device=device)
# Generate fake image batch with G
fake = netG(noise)
label.fill_(fake_label)
# Classify all fake batch with D
output = netD(fake.detach()).view(-1)
# Calculate D's loss on the all-fake batch
errD_fake = criterion(output, label)
# Calculate the gradients for this batch, accumulated (summed) with previous gradients
errD_fake.backward()
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
# Calculate gradients for G
errG.backward()
D_G_z2 = output.mean().item()
# Update G
optimizerG.step()
# Output training stats
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# Save Losses for plotting later
G_losses.append(errG.item())
D_losses.append(errD.item())
# Check how the generator is doing by saving G's output on fixed_noise
if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
with torch.no_grad():
fake = netG(fixed_noise).detach().cpu()
img_list.append(vutils.make_grid(fake, padding=2, normalize=True))
iters += 1
Starting Training Loop... [0/30][0/117] Loss_D: 1.9401 Loss_G: 6.0498 D(x): 0.6673 D(G(z)): 0.7023 / 0.0036 [0/30][50/117] Loss_D: 0.0741 Loss_G: 12.0091 D(x): 0.9484 D(G(z)): 0.0000 / 0.0000 [0/30][100/117] Loss_D: 0.4790 Loss_G: 2.3133 D(x): 0.7941 D(G(z)): 0.1109 / 0.1337 [1/30][0/117] Loss_D: 0.7951 Loss_G: 4.1812 D(x): 0.5847 D(G(z)): 0.0130 / 0.0384 [1/30][50/117] Loss_D: 0.2075 Loss_G: 6.2225 D(x): 0.9297 D(G(z)): 0.1054 / 0.0033 [1/30][100/117] Loss_D: 0.5663 Loss_G: 6.1435 D(x): 0.8443 D(G(z)): 0.2551 / 0.0038 [2/30][0/117] Loss_D: 0.8139 Loss_G: 5.0727 D(x): 0.7885 D(G(z)): 0.3430 / 0.0149 [2/30][50/117] Loss_D: 0.7764 Loss_G: 2.9057 D(x): 0.6604 D(G(z)): 0.1704 / 0.0984 [2/30][100/117] Loss_D: 0.6397 Loss_G: 3.8150 D(x): 0.8872 D(G(z)): 0.3576 / 0.0305 [3/30][0/117] Loss_D: 0.8877 Loss_G: 1.8565 D(x): 0.5540 D(G(z)): 0.1121 / 0.2080 [3/30][50/117] Loss_D: 0.3159 Loss_G: 5.1673 D(x): 0.8123 D(G(z)): 0.0380 / 0.0084 [3/30][100/117] Loss_D: 0.5099 Loss_G: 4.7001 D(x): 0.8573 D(G(z)): 0.2424 / 0.0164 [4/30][0/117] Loss_D: 0.6118 Loss_G: 3.6494 D(x): 0.7084 D(G(z)): 0.1315 / 0.0513 [4/30][50/117] Loss_D: 0.8808 Loss_G: 3.4359 D(x): 0.6725 D(G(z)): 0.2598 / 0.0538 [4/30][100/117] Loss_D: 0.7443 Loss_G: 2.0564 D(x): 0.5995 D(G(z)): 0.1177 / 0.1949 [5/30][0/117] Loss_D: 0.6123 Loss_G: 1.9673 D(x): 0.6685 D(G(z)): 0.1371 / 0.1746 [5/30][50/117] Loss_D: 0.5333 Loss_G: 2.9901 D(x): 0.7167 D(G(z)): 0.1272 / 0.0717 [5/30][100/117] Loss_D: 1.2035 Loss_G: 7.1999 D(x): 0.9343 D(G(z)): 0.5952 / 0.0021 [6/30][0/117] Loss_D: 0.7168 Loss_G: 1.9895 D(x): 0.6828 D(G(z)): 0.1887 / 0.1768 [6/30][50/117] Loss_D: 0.4794 Loss_G: 4.3665 D(x): 0.8629 D(G(z)): 0.2469 / 0.0188 [6/30][100/117] Loss_D: 0.6309 Loss_G: 3.2315 D(x): 0.7860 D(G(z)): 0.2611 / 0.0559 [7/30][0/117] Loss_D: 1.3193 Loss_G: 1.3704 D(x): 0.3891 D(G(z)): 0.0482 / 0.3284 [7/30][50/117] Loss_D: 0.4976 Loss_G: 2.3864 D(x): 0.8254 D(G(z)): 0.2135 / 0.1718 [7/30][100/117] Loss_D: 0.6764 Loss_G: 3.6391 D(x): 0.7983 D(G(z)): 0.2975 / 0.0488 [8/30][0/117] Loss_D: 0.3085 Loss_G: 3.7588 D(x): 0.8239 D(G(z)): 0.0829 / 0.0342 [8/30][50/117] Loss_D: 1.0106 Loss_G: 5.3503 D(x): 0.8928 D(G(z)): 0.5386 / 0.0080 [8/30][100/117] Loss_D: 0.4983 Loss_G: 4.5115 D(x): 0.8519 D(G(z)): 0.2311 / 0.0212 [9/30][0/117] Loss_D: 0.5727 Loss_G: 3.6715 D(x): 0.6652 D(G(z)): 0.0732 / 0.0566 [9/30][50/117] Loss_D: 0.4916 Loss_G: 3.3186 D(x): 0.9524 D(G(z)): 0.3206 / 0.0548 [9/30][100/117] Loss_D: 0.6399 Loss_G: 2.6318 D(x): 0.6357 D(G(z)): 0.0458 / 0.1121 [10/30][0/117] Loss_D: 0.3579 Loss_G: 3.9828 D(x): 0.8411 D(G(z)): 0.1394 / 0.0277 [10/30][50/117] Loss_D: 0.4766 Loss_G: 2.9532 D(x): 0.7345 D(G(z)): 0.0769 / 0.0775 [10/30][100/117] Loss_D: 0.3590 Loss_G: 3.8369 D(x): 0.8279 D(G(z)): 0.1367 / 0.0307 [11/30][0/117] Loss_D: 0.6152 Loss_G: 3.2281 D(x): 0.7813 D(G(z)): 0.2442 / 0.0637 [11/30][50/117] Loss_D: 0.6725 Loss_G: 2.4558 D(x): 0.7067 D(G(z)): 0.1614 / 0.1278 [11/30][100/117] Loss_D: 0.7881 Loss_G: 5.1566 D(x): 0.9080 D(G(z)): 0.4295 / 0.0104 [12/30][0/117] Loss_D: 0.5857 Loss_G: 3.9548 D(x): 0.8680 D(G(z)): 0.3135 / 0.0299 [12/30][50/117] Loss_D: 0.8012 Loss_G: 2.3201 D(x): 0.6978 D(G(z)): 0.2832 / 0.1470 [12/30][100/117] Loss_D: 0.9334 Loss_G: 2.8778 D(x): 0.7219 D(G(z)): 0.3534 / 0.0889 [13/30][0/117] Loss_D: 0.8605 Loss_G: 4.1145 D(x): 0.9221 D(G(z)): 0.4660 / 0.0335 [13/30][50/117] Loss_D: 0.3298 Loss_G: 3.6039 D(x): 0.8740 D(G(z)): 0.1554 / 0.0413 [13/30][100/117] Loss_D: 0.4438 Loss_G: 2.8206 D(x): 0.8089 D(G(z)): 0.1710 / 0.0807 [14/30][0/117] Loss_D: 0.9593 Loss_G: 3.1755 D(x): 0.8354 D(G(z)): 0.4676 / 0.0631 [14/30][50/117] Loss_D: 0.6441 Loss_G: 2.6513 D(x): 0.7146 D(G(z)): 0.2038 / 0.1002 [14/30][100/117] Loss_D: 0.6069 Loss_G: 1.8973 D(x): 0.6834 D(G(z)): 0.1546 / 0.1862 [15/30][0/117] Loss_D: 0.5693 Loss_G: 3.6300 D(x): 0.8735 D(G(z)): 0.3104 / 0.0403 [15/30][50/117] Loss_D: 0.4973 Loss_G: 2.5966 D(x): 0.7287 D(G(z)): 0.1310 / 0.1043 [15/30][100/117] Loss_D: 0.7844 Loss_G: 2.6907 D(x): 0.7094 D(G(z)): 0.2737 / 0.1071 [16/30][0/117] Loss_D: 1.4886 Loss_G: 5.1848 D(x): 0.9368 D(G(z)): 0.7001 / 0.0109 [16/30][50/117] Loss_D: 0.6792 Loss_G: 3.7189 D(x): 0.8590 D(G(z)): 0.3686 / 0.0364 [16/30][100/117] Loss_D: 0.5636 Loss_G: 2.8398 D(x): 0.8340 D(G(z)): 0.2757 / 0.0773 [17/30][0/117] Loss_D: 0.6149 Loss_G: 2.4283 D(x): 0.7727 D(G(z)): 0.2598 / 0.1147 [17/30][50/117] Loss_D: 0.4326 Loss_G: 3.0603 D(x): 0.8055 D(G(z)): 0.1638 / 0.0712 [17/30][100/117] Loss_D: 0.6199 Loss_G: 2.4742 D(x): 0.8491 D(G(z)): 0.3321 / 0.1134 [18/30][0/117] Loss_D: 0.4138 Loss_G: 2.7274 D(x): 0.7820 D(G(z)): 0.1176 / 0.0956 [18/30][50/117] Loss_D: 1.2467 Loss_G: 4.5077 D(x): 0.8354 D(G(z)): 0.5552 / 0.0802 [18/30][100/117] Loss_D: 0.9381 Loss_G: 0.8621 D(x): 0.5083 D(G(z)): 0.0946 / 0.4741 [19/30][0/117] Loss_D: 0.4609 Loss_G: 2.5669 D(x): 0.8318 D(G(z)): 0.2062 / 0.1075 [19/30][50/117] Loss_D: 1.6389 Loss_G: 0.4758 D(x): 0.2994 D(G(z)): 0.0795 / 0.6772 [19/30][100/117] Loss_D: 0.7331 Loss_G: 3.9918 D(x): 0.9654 D(G(z)): 0.4459 / 0.0281 [20/30][0/117] Loss_D: 0.7686 Loss_G: 3.4872 D(x): 0.8680 D(G(z)): 0.3934 / 0.0560 [20/30][50/117] Loss_D: 0.5526 Loss_G: 1.7059 D(x): 0.6885 D(G(z)): 0.1207 / 0.2491 [20/30][100/117] Loss_D: 1.5901 Loss_G: 5.2481 D(x): 0.9475 D(G(z)): 0.7185 / 0.0099 [21/30][0/117] Loss_D: 0.7896 Loss_G: 2.0150 D(x): 0.5920 D(G(z)): 0.1305 / 0.1725 [21/30][50/117] Loss_D: 0.5111 Loss_G: 2.9404 D(x): 0.8922 D(G(z)): 0.2919 / 0.0763 [21/30][100/117] Loss_D: 0.4811 Loss_G: 2.4759 D(x): 0.7656 D(G(z)): 0.1544 / 0.1147 [22/30][0/117] Loss_D: 0.6893 Loss_G: 1.7893 D(x): 0.6761 D(G(z)): 0.2048 / 0.2217 [22/30][50/117] Loss_D: 1.1274 Loss_G: 0.6827 D(x): 0.4792 D(G(z)): 0.1567 / 0.5611 [22/30][100/117] Loss_D: 0.5283 Loss_G: 2.4322 D(x): 0.7624 D(G(z)): 0.1906 / 0.1135 [23/30][0/117] Loss_D: 0.7917 Loss_G: 1.5314 D(x): 0.6370 D(G(z)): 0.2130 / 0.2896 [23/30][50/117] Loss_D: 0.4531 Loss_G: 2.3622 D(x): 0.7080 D(G(z)): 0.0722 / 0.1306 [23/30][100/117] Loss_D: 0.8905 Loss_G: 3.6310 D(x): 0.8616 D(G(z)): 0.4596 / 0.0411 [24/30][0/117] Loss_D: 0.9713 Loss_G: 4.5437 D(x): 0.9434 D(G(z)): 0.5414 / 0.0176 [24/30][50/117] Loss_D: 0.4375 Loss_G: 1.9606 D(x): 0.8002 D(G(z)): 0.1594 / 0.1783 [24/30][100/117] Loss_D: 1.6688 Loss_G: 1.0222 D(x): 0.2814 D(G(z)): 0.0505 / 0.4541 [25/30][0/117] Loss_D: 0.4607 Loss_G: 1.6043 D(x): 0.8016 D(G(z)): 0.1742 / 0.2646 [25/30][50/117] Loss_D: 0.5621 Loss_G: 2.7549 D(x): 0.8126 D(G(z)): 0.2659 / 0.0862 [25/30][100/117] Loss_D: 0.5063 Loss_G: 2.4228 D(x): 0.8183 D(G(z)): 0.2331 / 0.1154 [26/30][0/117] Loss_D: 0.6781 Loss_G: 1.6857 D(x): 0.7273 D(G(z)): 0.2694 / 0.2240 [26/30][50/117] Loss_D: 0.7238 Loss_G: 3.5195 D(x): 0.8820 D(G(z)): 0.3923 / 0.0488 [26/30][100/117] Loss_D: 0.4475 Loss_G: 2.8288 D(x): 0.7856 D(G(z)): 0.1524 / 0.0818 [27/30][0/117] Loss_D: 0.7167 Loss_G: 1.5080 D(x): 0.6206 D(G(z)): 0.1531 / 0.2879 [27/30][50/117] Loss_D: 0.6671 Loss_G: 3.4803 D(x): 0.9097 D(G(z)): 0.3896 / 0.0433 [27/30][100/117] Loss_D: 1.9734 Loss_G: 4.1894 D(x): 0.9101 D(G(z)): 0.7622 / 0.0250 [28/30][0/117] Loss_D: 0.7759 Loss_G: 2.9439 D(x): 0.8034 D(G(z)): 0.3646 / 0.0768 [28/30][50/117] Loss_D: 0.5434 Loss_G: 1.9894 D(x): 0.7618 D(G(z)): 0.2008 / 0.1761 [28/30][100/117] Loss_D: 2.3222 Loss_G: 4.4351 D(x): 0.9669 D(G(z)): 0.8506 / 0.0285 [29/30][0/117] Loss_D: 0.7520 Loss_G: 1.9215 D(x): 0.6003 D(G(z)): 0.1386 / 0.1894 [29/30][50/117] Loss_D: 0.7850 Loss_G: 1.3052 D(x): 0.5874 D(G(z)): 0.1543 / 0.3272 [29/30][100/117] Loss_D: 0.4855 Loss_G: 2.8340 D(x): 0.8174 D(G(z)): 0.2178 / 0.0756
Finally, lets check out how we did. Here, we will look at three different results. First, we will see how D and G’s losses changed during training. Second, we will visualize G’s output on the fixed_noise batch for every epoch. And third, we will look at a batch of real data next to a batch of fake data from G.
Loss versus training iteration
Below is a plot of D & G’s losses versus training iterations.
plt.figure(figsize=(10,5))
plt.title("Generator and Discriminator Loss During Training")
plt.plot(G_losses,label="G")
plt.plot(D_losses,label="D")
plt.xlabel("iterations")
plt.ylabel("Loss")
plt.legend()
plt.show()
Visualization of G’s progression
Remember how we saved the generator’s output on the fixed_noise batch after every epoch of training. Now, we can visualize the training progression of G with an animation. Press the play button to start the animation.
#%%capture
fig = plt.figure(figsize=(10,10))
plt.axis("off")
ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
ani = animation.ArtistAnimation(fig, ims, interval=300, repeat_delay=1000, blit=True)
f = r"c://Users/jbickelhaupt/Desktop/animation2.gif"
writergif = animation.PillowWriter(fps=2)
ani.save(f, writer=writergif)
Real Images vs. Fake Images
Finally, lets take a look at some real images and fake images side by side.
# Grab a batch of real images from the dataloader
# real_batch = next(iter(dataloader))
# Plot the real images
# plt.figure(figsize=(15,15))
# plt.subplot(1,2,1)
# plt.axis("off")
# plt.title("Real Images")
# plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))
# Plot the fake images from the last epoch
fig = plt.figure(figsize=(70,70), dpi=500)
# plt.subplot(1,2,2)
plt.axis("off")
plt.title("Fake Images")
# plt.imshow(np.transpose(img_list[-1],(1,2,0)))
plt.imshow(np.transpose(img_list[-1]))
plt.show()
# plt.subplot(1,2,2)
plt.axis("off")
plt.figure(figsize=(30,30), dpi=200)
plt.imshow(np.transpose(img_list[-1],(1,2,0)))
plt.show()
We have reached the end of our journey, but there are several places you could go from here. You could:
here <https://github.com/nashory/gans-awesome-applications>__music <https://www.deepmind.com/blog/wavenet-a-generative-model-for-raw-audio/>__